<!--  -->
<template>
  <div class="">
     <crumb  title="首页" title2="商品管理" title3="商品分类"></crumb >
    <el-card>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-button type="primary" @click="showAdd('', false)">添加分类</el-button>
        </el-col>
      </el-row>
      <zk-table
        :data="tableData"
        style="margin-top: 15px"
        :columns="columns"
        :show-index="true"
        :expand-type="false"
        :selection-type="false"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showAdd(scope.row.cat_id, true)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="showDelet(scope.row.cat_id)"
          >
            删除</el-button
          >
        </template>
      </zk-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose1"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="ruleForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="roleDesc">
          <el-cascader
            style="width: 100%"
            v-model="value"
            :options="options"
            @change="handleChange"
            :props="cascaderPros"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      uersname: "",
      dialogVisible: false,
      tableData: [],
      queryInfo: {
        query: 3,
        pagenum: 1,
        pagesize: 5,
      },
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      total: 0,
      ruleForm: {
        cat_name: "",
        cat_level: 0,
        cat_pid: 0,
      },
      options: [],
      rules: {
        cat_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      value: "",
      cascaderPros: {
        value: "cat_id",
        label: "cat_name",
        checkStrictly: true,
      },
      toggle: true,
      updataid: 0,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async showDelet(id) {
      const confirmResult = await this.$confirm(" 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
      if (confirmResult == "confirm") {
        const { data: res } = await this.myaxios.delete(`categories/${id}`);
      }
      this.getData();
    },
    handleChange() {
      if (this.value.length == 1) {
        this.ruleForm.cat_pid = this.value[0];
        this.ruleForm.cat_level = 1;
        console.log(this.ruleForm.cat_level);
      } else if (this.value.length == 2) {
        this.ruleForm.cat_pid = this.value[1];
        this.ruleForm.cat_level = 2;
      } else {
        this.ruleForm.cat_pid = 0;
        this.ruleForm.cat_level = 0;
      }
    },
    handleClose1() {
      this.dialogVisible = false;
      this.$refs.ruleForm.resetFields();
      this.value = [];
      this.ruleForm.cat_pid = 0;
      this.ruleForm.cat_level = 0;
    },
    async add() {
      console.log(!this.toggle);
      if (!this.toggle) {
    
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) return;
          const { data: res } = await this.myaxios.post("categories", this.ruleForm);
          this.$message.success("成功!");
          console.log(res)
          this.handleClose1();
          this.getData();
        });
      } else {
        
        const { data: res } = await this.myaxios.put(`categories/${this.updataid}`, {
          cat_name: this.ruleForm.cat_name,
        });
        if (res.meta.status !== 200) {
          this.$message.error("失败！");
        } else {
          this.getData();
          this.$message.success("成功！");
          this.handleClose1();
        }
        this.toggle = true;
      }

    },
    async showAdd(id, e) {
      this.getParentCatelist();
      this.dialogVisible = true;
      this.toggle = e;
      if (e) {
        this.updataid = id;
        // console.log(id);
        this.toggle = true;
        const { data: res } = await this.myaxios.get(`categories/${id}`);
        // this.ruleForm=id
        // console.log(res);
        this.value = [];
        this.ruleForm.cat_name = res.data.cat_name;
        this.ruleForm.cat_pid = res.data.cat_pid;
        this.ruleForm.cat_level = res.data.cat_level;
        if (this.ruleForm.cat_level == 1) {
          this.value = [res.data.cat_pid];
        } else if (this.ruleForm.cat_level == 2) {
          var pid = res.data.cat_pid;
          const { data: res2 } = await this.myaxios.get(`categories/${pid}`);
          // console.log(res2);
          this.value.push(res2.data.cat_pid);
          this.value.push(pid);
          console.log(this.value);
        }
      } else {
        this.toggle = false;
      }
    },
    async getParentCatelist() {
      const { data: res } = await this.myaxios.get("categories", {
        params: { type: 2 },
      });
      this.options = res.data;
      // console.log(res);
    },
    handleSizeChange(size) {
      this.queryInfo.pagenum = 1;
      this.queryInfo.pagesize = size;
      this.getData();
    },
    handleCurrentChange(num) {
      this.queryInfo.pagenum = num;
      this.getData();
    },
    async getData() {
      const { data: res } = await this.myaxios.get("categories", {
        params: this.queryInfo,
      });
      // console.log(res);
      this.tableData = res.data.result;
      this.total = res.data.total;
    },
    handleUpate() {},
    handleDelete() {
      this.dialogVisible = false;
      this.$refs.ruleForm.resetFields();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getData();
  },

  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped></style>
